package com.zaaach.citypicker.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.zaaach.citypicker.model.City;

import java.util.ArrayList;
import java.util.List;

public class DBDao {
    private DataBase dbs;
    public DBDao(Context context){
        dbs = new DataBase(context);
    }


    public boolean save(String id, String name, String lsh){
        try {
            String sql ="insert into cityinfo(id,name,pinyin) values(?,?,?)";
            SQLiteDatabase db = dbs.getWritableDatabase();
            db.execSQL(sql,new Object[]{id,name,lsh});
            Log.i("数据库","插入数据成功");
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    //查询所有数据
    public List<City> findAll(){
        String sql = "select * from cityinfo";
        SQLiteDatabase db = dbs.getReadableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        List<City> list = new ArrayList<>();
        if(cursor!=null && cursor.getCount()>0){
            while (cursor.moveToNext()){
                String id = cursor.getString(0);
                String name = cursor.getString(1);
                String pinyin = cursor.getString(2);
                City city = new City(name,pinyin,id);
                list.add(city);
            }
            cursor.close();
            return list;
        }
        return null;
    }
    //查询所有数据
    public List<City> findByAll(String name){
        String sql = "select * from cityinfo where name like ? ";
        SQLiteDatabase db = dbs.getReadableDatabase();
        Cursor cursor = db.rawQuery(sql, new String[]{"%"+name+"%"});
        List<City> list = new ArrayList<>();
        if(cursor!=null && cursor.getCount()>0){
            while (cursor.moveToNext()){
                String id = cursor.getString(0);
                String namea = cursor.getString(1);
                String pinyin = cursor.getString(2);
                City city = new City(namea,pinyin,id);
                list.add(city);
            }
            Log.i("数据库","查询数据成功:"+list.get(0).toString());
            cursor.close();
            return list;
        }
        return null;
    }

    public void delete(){
        String sql = "delete from cityinfo";
        SQLiteDatabase db = dbs.getWritableDatabase();
        db.execSQL(sql);
    }

}
